package br.brpv.silvestrin.vendas.webservice;

import br.brpv.silvestrin.vendas.mainactivity.MainActivity;
import br.brpv.silvestrin.vendas.util.Encryption;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class WebService extends AsyncTask<Object, Integer, SoapObject> {
	private WSRequestCompleteListener<SoapObject> callback;
	private ProgressDialog dialog;
	private String progressMessage;
	private Context context;
	
	private static final String NAMESPACE = "http://microsoft.com/webservices/";
	
	private String soapAction = "";

	private static String url = "";
	private static String user = "";
	private static String password = "";
	
	public enum  Method {
		HELLO_WORLD, VALIDA_USUARIO, F_GET_PACKAGE, F_GET_VALOR_PACKAGE
	}
	
	private SoapSerializationEnvelope envelope;
	
	public WebService(Context context, String message, WSRequestCompleteListener<SoapObject> cb) {
		super();
		this.context = context;
		this.progressMessage = message;
		this.callback = cb;
	}

	/**
	 * Metodo é executado quando o método Execute é chamado. 
	 * 
	 * @param params Array de parametros do tipo Object. O primeiro 
	 * parametro deve ser do tipo Method que indica qual o metodo 
	 * do settings_webservice será executado.
	 * 
	 * @return strinf de resposta do web service. 
	 */
	@Override
	protected SoapObject doInBackground(Object... params) {
		SoapObject request = initSoapRequest(params);
	    
	    envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	    envelope.dotNet = true;
	    envelope.setOutputSoapObject(request);

	    HttpTransportSE httpRequest = new HttpTransportSE(url, 60*1000);
        httpRequest.debug = true;

        System.out.println("URL = " + url + "\n" + soapAction + "\n" + request);

	    try {
	        httpRequest.call(soapAction, envelope);
	    }
	    catch(Exception e) {
	        e.printStackTrace();
	    }

        if(envelope.bodyIn == null || envelope.bodyIn.getClass() != SoapObject.class) return null;
		return (SoapObject) envelope.bodyIn;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
        dialog = new ProgressDialog(context);
        if(progressMessage != null && !this.progressMessage.equals("")){ //se nao houver mensagem nao mostra
            dialog.setMessage(this.progressMessage);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
        MainActivity.setRefreshing(true);
	}

	@Override
	protected void onPostExecute(SoapObject result) {
		super.onPostExecute(result);
		
		if(dialog.isShowing()) {
			dialog.dismiss();
		}
		callback.onTaskComplete(result);
        MainActivity.setRefreshing(false);
	}

	private SoapObject helloWorldRequest(String param) {
		String METHOD_HELLO_WORLD = "HelloWorld";
		SoapObject request = new SoapObject(NAMESPACE, METHOD_HELLO_WORLD);
		
		PropertyInfo quotesProperty = new PropertyInfo();
	    quotesProperty.setName("symbol");
	    quotesProperty.setValue(param);
	    quotesProperty.setType(String.class);
	    request.addProperty(quotesProperty);
	    
	    soapAction = NAMESPACE + METHOD_HELLO_WORLD;
	    
		return request;		
	}
	
	private SoapObject validateUserRequest(String user, String password) {
		String METHOD_VALIDA_USUARIO = "fgValidaUsuario";
		SoapObject request = new SoapObject(NAMESPACE, METHOD_VALIDA_USUARIO);
		
		request.addProperty("paUser", user);
	    request.addProperty("paSenha", password);	    
	    request.addProperty("paMError", "");
	    
	    soapAction = NAMESPACE + METHOD_VALIDA_USUARIO;
		
		return request;	
	}
	
	private SoapObject fGetPackage(String paPackage, String paParametros) {
		String METHOD_FGETPACKAGE = "fGetPakage";
		SoapObject request = new SoapObject(NAMESPACE, METHOD_FGETPACKAGE);
		
		request.addProperty("paUser", user);
	    request.addProperty("paSenha", password);	    
	    request.addProperty("paMError", "");
	    request.addProperty("paPackage", paPackage);
	    request.addProperty("paParametros", paParametros);
	    
	    soapAction = NAMESPACE + METHOD_FGETPACKAGE;
		
		return request;	
	}

    private SoapObject fGetValorPackage(String paPackage, String paParametros) {
        String METHOD_FGETVALORPACKAGE = "fGetValorPackage";
        SoapObject request = new SoapObject(NAMESPACE, METHOD_FGETVALORPACKAGE);

        request.addProperty("paUser", user);
        request.addProperty("paSenha", password);
        request.addProperty("paMError", "");
        request.addProperty("paPackage", paPackage);
        request.addProperty("paParametros", paParametros);

        soapAction = NAMESPACE + METHOD_FGETVALORPACKAGE;

        return request;
    }
	
	private SoapObject initSoapRequest(Object[] params) {
		Method method = (Method)params[0];
		SoapObject ret = null;
		
		switch(method) {
			case HELLO_WORLD:
				if(params.length == 2 && 
						params[1].getClass() == String.class) {	
					ret = helloWorldRequest((String)params[1]);
				}
				break;
				
			case VALIDA_USUARIO:
				if(params.length == 3 && 
						params[1].getClass() == String.class && 
						params[2].getClass() == String.class) {	
					try {
						ret = validateUserRequest(Encryption.encrypt((String)params[1]), Encryption.encrypt((String)params[2]));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				break;
				
			case F_GET_PACKAGE:
				if(params.length == 3 &&
						params[1].getClass() == String.class && 
						params[2].getClass() == String.class) {
					ret = fGetPackage((String)params[1], (String)params[2]);
				}
				break;

            case F_GET_VALOR_PACKAGE:
                if(params.length == 3 &&
                        params[1].getClass() == String.class &&
                        params[2].getClass() == String.class) {
                    ret = fGetValorPackage((String)params[1], (String)params[2]);
                }
                break;
				
			default:ret = null;		
		}		
		
		return ret;
	}
	
	public static void setUser(String user) {
		try {
			WebService.user = Encryption.encrypt(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void setPassword(String password) {
		try {
			WebService.password = Encryption.encrypt(password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void setURL(String newUrl) {
		url = newUrl;
	}

}